The Object class is useful if you want to refer any object whose type you don't know. Note that parent class reference variable can refer the child class object, know as upcasting.
Now ,we taken an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't what object would be returned from this method
The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc.
For Example: Object Cloning
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"anupam");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
Output: 101 anupam
101 anupam
Leave Comment